package com.alianzamedica.controllers;

import java.sql.*;
import java.util.*;

import javax.servlet.http.*;

import org.apache.struts.action.*;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.objectsearch.web.tools.Converter;
import org.w3c.dom.Document;
import com.alianzamedica.businessobject.*;
import com.alianzamedica.connection.ConnectionImpl;
import com.alianzamedica.controllers.prescription.PrescriptionHelper;
import com.alianzamedica.models.DrugSelectModel;
import com.alianzamedica.servlets.PrescriptionUpdater;
import com.alianzamedica.tools.Enviroment;
import com.alianzamedica.view.PrescriptionForm;

/**
 * @author Carlos
 * 
 */
public class RegisterPrescriptionAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String action = "success";
		Converter converter = new Converter();
		request.setAttribute("format", converter);
		PrescriptionForm pForm = (PrescriptionForm) form;
		PrescriptionHelper util = new PrescriptionHelper();
		HttpSession session = request.getSession();
		Doctor doctor = (Doctor) session.getAttribute("doctor");
		Prescription prescription = (Prescription) session
				.getAttribute("prescription");
		if (prescription != null) {
			String tag = pForm.getTag();
			tag.replaceAll("0x", "");
			prescription.setTag(tag);
			prescription.setPatientId(Converter.string2Integer(pForm
					.getPacienteId()));
			prescription.setExpedition(new java.util.Date());
			if (doctor != null) {
				prescription.setDoctorId(doctor.getId());
			}
			String guardar = pForm.getGuardar();
			if (guardar.equalsIgnoreCase("guardar")) {
				action = "success";
				guardarPrescripcion(prescription);
				session.removeAttribute("prescription");
				request.setAttribute("prescription", prescription);
			} else {
				String idVal = request.getParameter("id");
				Integer id = Converter.string2Integer(idVal);
				Integer detail = Converter.string2Integer(request
						.getParameter("detail"));
				String busqueda= request.getParameter("name");
				List list = util.showDrugs(doctor.getId(),busqueda);

				request.setAttribute("drugs", list);
				if (detail != null) {
					PrescriptionDetail prescriptionDetail = prescription
							.getDetail().get(detail.intValue());
					request.setAttribute("prescriptionDetail",
							prescriptionDetail);
				} else {
					if (id != null) {
						PrescriptionDetail pd = new PrescriptionDetail();
						pd.setDrugId(id);
						request.setAttribute("prescriptionDetail", pd);
					}
				}

				action = "detail";

			}
		}
		return mapping.findForward(action);
	}

	private void guardarPrescripcion(Prescription prescription)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		Integer prescriptionId = prescription.getId();
		if (prescriptionId != null) {

			PrescriptionDetail detalleBorrar = new PrescriptionDetail();
			detalleBorrar.setPrescriptionId(prescriptionId);
			search.deleteObject(detalleBorrar);

			search.addBatchObject(prescription);
			search.executeBatchUpdate();

		} else {
			prescriptionId = this.getNextFromPrescription();
			prescription.setId(prescriptionId);
			search.addBatchObject(prescription);
			search.executeBatch();
		}

		Iterator<PrescriptionDetail> details = prescription.getDetail()
				.iterator();
		while (details.hasNext()) {
			PrescriptionDetail prescriptionDetail = (PrescriptionDetail) details
					.next();
			prescriptionDetail.setPrescriptionId(prescriptionId);
			search.addBatchObject(prescriptionDetail);
		}
		search.executeBatch();
	}

	/**
	 * @return
	 */
	private int getNextFromPrescription() {
		String sql = "select ifnull(max(prescription_id),0)+1 as NEXTID from prescription";
		ConnectionImpl connectionImpl = new ConnectionImpl();
		Statement stmt = null;
		ResultSet rs = null;
		int next = 1;
		try {
			connectionImpl.open();
			Connection con = connectionImpl.getConnection();
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while (rs.next()) {
				next = rs.getInt("NEXTID");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
			} catch (Exception e2) {
			}
			try {
				rs.close();
			} catch (Exception e2) {
			}
			try {
				connectionImpl.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return next;
	}

}
